<template>
  <md-nav-bar
    color="white"
    leftIcon="home"
    backUrl="/pages/index/index"
    :bgInfo="{ url: 'https://cdn.xmxiaomai.com/isong_static/common/login_bg.png', height: '802rpx' }" />
  <view class="container">
    <!-- logo -->
    <view class="logo-section">
      <view class="welcome">创作者的伴侣、爱好者的导师、教学者的工具</view>
    </view>
    <!-- 首次登录赠送 -->
    <view class="gift">首次登录赠送 {{ data.config?.registerBonusPoint || 0 }} A豆</view>
    <template v-if="!data.otherLogin">
      <!-- 微信一键登录按钮 -->
      <button
        class="btn-wechat"
        :open-type="checked ? 'getPhoneNumber' : undefined"
        @click="handlePhone"
        @getphonenumber="wechatLogin">
        手机号快捷登录
      </button>
      <!-- 其他手机号登录 -->
      <button class="btn-phone" @click="phoneLogin">使用其他手机号登录</button>
    </template>
    <view class="form-mes" v-else>
      <view class="input-item">
        <view class="num">+86</view>
        <input v-model="data.formdata.phone" class="item" maxlength="11" placeholder="请输入手机号" type="number" />
      </view>
      <view class="input-item">
        <input v-model="data.formdata.code" class="item" maxlength="6" placeholder="请输入验证码" type="number" />
        <view @click="getMsgCode" :class="['code', data.showCountDown ? 'active' : '']">
          {{ data.showCountDown ? `${data.countdown}s后重新获取` : '获取验证码' }}
        </view>
      </view>
      <button class="btn-wechat" @click="handleLogin">登录</button>
      <button class="btn-phone" @click="handleBackLogin">返回快捷登录</button>
    </view>
    <!-- 协议 -->
    <view class="protocol">
      <checkbox :checked="checked" @click="checked = !checked" color="#009966" />
      <text>已阅读并同意</text>
      <md-agreement text="用户协议" />
    </view>

    <view class="back-home" @click="backHome()">
      <text>《 返回首页</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
// 接口
import Api from '@/api';
import type { Auth, Common } from '@/api/data';

const data = reactive({
  otherLogin: false,
  loginCode: '',
  formdata: {
    phone: '',
    code: '',
  },
  showCountDown: false,
  countdown: 60,
  timer: 0,
  config: {} as Common.Configuration.Data,
});

const checked = ref(false);

// 处理用户要优先勾选同意协议
const handlePhone = () => {
  if (!checked.value) {
    uni.showToast({ title: '请先同意协议', icon: 'none' });
    return;
  }
};

function wechatLogin(e: any) {
  // 微信登录逻辑
  if (!e.detail?.code) {
    // 用户拒绝授权或授权失败
    console.log('微信手机号授权失败:', e.detail.errMsg);
    uni.showToast({
      title: '授权失败，请重试',
      icon: 'none',
    });
    return;
  }
  fetchWxLogin({ phoneCode: e.detail.code });
}

function phoneLogin() {
  // 跳转手机号登录
  data.otherLogin = true;
}

/**
 * 其他手机号登录
 */
// 倒计时60秒
const countDown = () => {
  data.timer = setInterval(() => {
    data.countdown -= 1;
    if (data.countdown <= 0) {
      clearInterval(data.timer);
      data.countdown = 60; // 重置倒计时时间
      data.showCountDown = false;
    }
  }, 1000);
};

// 获取验证码
const getMsgCode = () => {
  if (!data.formdata.phone) {
    uni.showModal({
      title: '提示',
      content: '请输入手机号',
      showCancel: false,
    });
    return;
  }
  if (data.showCountDown) return;
  data.showCountDown = true;
  // 执行倒计时
  countDown();
  // 执行获取验证码接口
  fetchGetMsgCode();
};

// 手机号 + 验证码登录
const handleLogin = () => {
  if (!checked.value) {
    uni.showToast({ title: '请先同意协议', icon: 'none' });
    return;
  }
  if (!data.formdata.phone || !data.formdata.code) {
    uni.showToast({
      icon: 'none',
      title: '手机号或者验证码未填！',
    });
    return;
  }
  fetchPhoneLogin();
};

// 返回一键登录
const handleBackLogin = () => {
  data.otherLogin = false;
  data.formdata = {
    phone: '',
    code: '',
  };
  if (data.countdown <= 0) {
    clearInterval(data.timer);
    data.countdown = 60; // 重置倒计时时间
    data.showCountDown = false;
  }
};

/**
 * 接口相关
 */
// 微信登录获取user_wx_id
const fetchWxLogin = async (params: Partial<Auth.Login.Body>) => {
  uni.showLoading({ title: '登录中', mask: true });
  // 通过邀请绑定用户的处理
  const parentId = uni.getStorageSync('parentId') || undefined;
  try {
    const res = await Api.Auth.login({ loginCode: data.loginCode, state: 'default', parentId, ...params });
    uni.setStorageSync('auth', res.data);
    uni.navigateBack();
  } catch (e: any) {
    //TODO handle the exception
    uni.showToast({
      title: e?.message || e,
      icon: 'error',
    });
  }
  uni.hideLoading();
};

// 获取短信验证码
const fetchGetMsgCode = async () => {
  try {
    await Api.Auth.sendSmsCode({
      mobile: data.formdata.phone,
      scene: 1,
    });
    uni.showToast({
      title: '短信发送成功',
    });
  } catch (error: any) {
    uni.showToast({
      title: error?.msg || error,
      icon: 'error',
    });
  }
};

// 手机号 + 验证码登录
const fetchPhoneLogin = async () => {
  uni.showLoading({ title: '登录中', mask: true });
  // 通过邀请绑定用户的处理
  const parentId = uni.getStorageSync('parentId') || undefined;
  try {
    const res = await Api.Auth.smsLogin({
      mobile: data.formdata.phone,
      code: data.formdata.code,
      parentId,
      socialType: 34,
      socialCode: data.loginCode,
      socialState: 'default',
    });
    uni.setStorageSync('auth', res.data);
    uni.navigateBack();
  } catch (error: any) {
    uni.showToast({
      title: error?.msg || error,
      icon: 'error',
    });
  }
  uni.hideLoading();
};

const backHome = () => {
  uni.reLaunch({
    url: '/pages/index/index',
  });
};

onLoad(() => {
  data.config = uni.getStorageSync('config');
  uni.login({
    provider: 'weixin', //使用微信登录
    success: function (res) {
      console.log(res);
      data.loginCode = res.code;
    },
  });
});

onShow(() => {
  // 接收下一个页面带回来的参数
  uni.$once('userAgreement', function (data) {
    if (data?.agree) {
      checked.value = data?.agree;
    }
  });
});
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  position: relative;
}
.logo-section {
  text-align: center;
  position: relative;
  .welcome {
    position: absolute;
    color: #fff;
    font-size: 28rpx;
    bottom: 220rpx;
    font-weight: bold;
    width: 100%;
    text-align: center;
    letter-spacing: 1rpx;
  }
}
.gift {
  text-align: center;
  color: #333;
  font-size: 30rpx;
  margin: 80rpx 0 40rpx 0;
  font-weight: 500;
}
.btn-wechat {
  width: 80vw;
  margin: 0 auto 30rpx auto;
  background: #3ec06c;
  color: #fff;
  font-size: 32rpx;
  border-radius: 50rpx;
  height: 90rpx;
  line-height: 90rpx;
  border: none;
  display: block;
  font-weight: 500;
  &.cancel {
    border: 1rpx solid #3ec06c;
    background: white;
  }
}
.btn-phone {
  width: 80vw;
  margin: 0 auto 0 auto;
  background: #fff;
  color: #009966;
  font-size: 32rpx;
  border-radius: 50rpx;
  height: 90rpx;
  line-height: 90rpx;
  border: 2rpx solid #009966;
  display: block;
  font-weight: 500;
}
.protocol {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 60rpx;
  font-size: 26rpx;
  color: #333;
  .link {
    color: #009966;
    margin-left: 6rpx;
    text-decoration: underline;
  }
}

.form-mes {
  width: 80%;
  margin: 0 auto;
  .input-item {
    display: flex;
    align-items: center;
    height: 80rpx;
    margin-bottom: 20rpx;
    border-bottom: 1rpx solid #ddd;
    input {
      flex: 1;
    }
  }
  .num {
    padding: 0 20rpx;
    border-right: 1rpx solid #ddd;
  }
  .code {
    &.active {
      color: #ddd;
    }
  }
}

.back-home {
  width: 100%;
  text-align: center;
  position: fixed;
  bottom: 80rpx;
  font-size: 28rpx;
  color: #6a6a6a;
  margin-left: -5px;
}
</style>
